<template>
    <div>
        <Row style="margin:5px 0px 10px 5px">
            <i-col span="1" >
                <Button  size="default"  type="primary" @click="btn_refresh">刷新</Button>
            </i-col>
            <i-col span="8" offset="1" style="text-align:center">
                <p>提示:  禁用后的菜单在编辑时无法查看</p>
            </i-col>
        </Row>

        <i-table size="default"   border stripe  :columns="format" :data="show_list" :height="sharedState.tableHeight" > 
            <template slot-scope="{ row, index }" slot="action">
                <Button  size="default"   v-if="show_list[index].name !='超管' && show_list[index].name !='超级管理员'" type="primary" style="margin-bottom: 5px ;margin-right:5px"  @click="edit_role(index)">编辑</Button>
            </template> 
        </i-table >
        <div style="text-align: center;margin-top: 10px;">
            <Page ref="page" :total="total" :page-size="pageSize"  @on-change="changePage" show-total/>
        </div>
        <!-- 显示编辑角色模态框 -->
        <Modal v-model="show_edit_role_modal" width="600" draggable>
            <p slot="header" style="color:#f60;text-align:center">
                <span> 编辑角色</span>
            </p>
            <div>
                <Form ref="role" >
                    <Form-Item >
                        <!-- 每个树节点用来作为唯一标识的属性，整棵树应该是唯一的 -->
                        <el-tree :data="perm_data"  
                            show-checkbox   
                            node-key="menu_id"  
                            ref="tree" 
                            highlight-current
                            @check="handleCheck"  
                            :props="defaultProps">
                        </el-tree>
                    </Form-Item>
                </Form>
            </div>
            <div slot="footer">
                <!-- role是Form  ref的值 -->
                <Button  size="default"  type="primary"   @click="submit_edit_role('role')">提交</Button>
            </div>
        </Modal>
    </div>
    
</template>

<script>

import { role_list,get_menu_tree,get_role_perm,update_role_perm } from  '@/api'
import { post } from '@/api/http'
import store from '@/store'

export default {
    data() {
        return {
            sharedState: store.state,
            format: [
                {
                    title: '角色名称',key: 'name'
                },
                {
                    title: '权限组',key: 'perm_group'
                },
                {
                    title: '权限列表(叶子结点)',key: 'perms', ellipsis: true,tooltip: true,
                },
                {
                    title: '权限树（完整树）',key: 'perms_all', ellipsis: true,tooltip: true,
                },
                {
                    title: '操作',slot: 'action',width: 100,align: 'center'
                }
            ],

            total_list: [],
            show_list: [],
            // 分页
            total: 0,
            pageSize: 10,
        
            // 整个菜单树
            perm_data: [],
            select_data: [],
            show_edit_role_modal: false,        
            defaultProps: {
                label: 'name',
                children: 'children'
            },
            // 编辑
            isedit:false, 
            // 编辑的角色id
            role_id: null,
            //用户点击复选框设置key，需要传给后台保存,格式为字符串"1,2,3"
            perms: "",
            // 用户点击复选框设置key+半开key，需要传给后台保存,格式为字符串"1,2,3"
            perms_all: "",
            count: 1,
        }
    },
    methods: {
		btn_refresh(){
            this.refresh()
        },
        changePage(index) {
            let _start = (index -1) * this.pageSize
            let _end = index * this.pageSize
            this.show_list = this.total_list.slice(_start,_end)
        },
        handleNodeClick(data) {
            console.log(data);
        },
        // 当复选框被点击的时候触发
        // 传递给 data 属性的数组中该节点所对应的对象、树目前的选中状态对象，包含 checkedNodes、checkedKeys、halfCheckedNodes、halfCheckedKeys 四个属性
        handleCheck(data, checked ) {
            this.isedit = true
            console.log("checked.halfCheckedKeys.length:",checked.halfCheckedKeys.length)
            console.log("data,checked:",data,checked)
            console.log("checked.checkedKeys",checked.checkedKeys)
            this.perms = checked.checkedKeys.join(",")
            // bug 
            if (checked.halfCheckedKeys.length > 0){
                this.perms_all = checked.checkedKeys +","+ checked.halfCheckedKeys
            }else {
                this.perms_all = checked.checkedKeys.join(",")
            }
            
            console.log("this.perms:",this.perms)
            console.log("this.perms_all:",this.perms_all)
        },

        getCheckedKeys() {
            console.log("this.$refs.tree.getCheckedKeys：",this.$refs.tree.getCheckedKeys());
        },

        setCheckedKeys(keys) {
            // this.$refs.tree.setCheckedKeys([3]]);
            this.$refs.tree.setCheckedKeys(keys);
        },
        resetChecked() {
            this.$refs.tree.setCheckedKeys([]);
        },

        // 提交编辑按钮事件
        // bug 加入没有变更就提交 获取到的perms perms_all是空的
        // 1 判断无变更就不提交 
        submit_edit_role(name){
            console.log(name)
            console.log("this.perms.length：",this.perms.length)
            // 假如清空也是 0
            if (! this.isedit){
                this.$Message.info("用户角色无变更")
                return
            }
            let data = JSON.stringify({"id":this.role_id,"perms":this.perms,"perms_all":this.perms_all})
            console.log("提交data:"+data)
            // 判断无变更

            post(update_role_perm,data).then( response => {
                let res = JSON.stringify(response.data)
                console.log("res:",res)
                if(res.indexOf('ok') != -1){
                    this.$Message.success("保存成功")
                    this.show_edit_role_modal = false
                    this.refresh()
                } else{
                    alert(res)
                }
            })

        },
        // 点击编辑角色按钮事件
        edit_role(index){
            console.log(this.show_list[index].name)
            // 重置编辑变量
            this.isedit  = false
            this.perms = ""
            this.perms_all = ""
            // 获取用户的权限
            // 这里只能设置 选中key，不包含半开key，不然的话，勾选了父菜单，底下子菜单全部会勾选
            let role_id = this.show_list[index].id
            this.role_id = role_id 
            let name = this.show_list[index].name
            let data = JSON.stringify({"role_id":role_id,"role_name":name})
            post(get_role_perm,data).then( (response) => {
                // 只需要获取到权限菜单的叶子结点
                let perms = response.data
                this.setCheckedKeys(perms)
            })
            this.show_edit_role_modal= true
        },
        refresh() {
            // 获取整个菜单树 可以放在整个首页刷新,保存到state中
            post(get_menu_tree).then( (response) => {
                this.perm_data = response.data
            })
            post(role_list).then( (response) => {
                // this.show_list = response.data
                this.total_list = response.data
                this.total = response.data.length
                if(this.total < this.pageSize) {
                    this.show_list = this.total_list
                }else {
                    // 修改改数据之后显示回到第一页的bug，改为停留在当前页
                    let currentPage = this.$refs.page.currentPage
                    let _start = (currentPage-1) * this.pageSize
                    let _end = currentPage * this.pageSize
                    this.show_list = this.total_list.slice(_start,_end)
                }
            })
        }
    },
    mounted: function() {
        setTimeout(() =>{
            this.refresh();
        },200); 
    }
}
</script>
<style scoped>

</style>